import React from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router';
import { hashHistory  } from 'react-router';
require("./home.css");

class ChangePhone extends React.Component{

    constructor() {
        super();
        const userSessionStorage = JSON.parse(window.sessionStorage.getItem('userStorage'));
        this.state = {
            newPhone: '',
            loginID: userSessionStorage.user_id
        };
    }

    // 表单提交按钮监听事件，连接服务器，
    handleSubmit(e){
        e.preventDefault();
        const userSessionStorage = JSON.parse(window.sessionStorage.getItem('userStorage'));
        const changePhone = ReactDOM.findDOMNode(this.refs.changePhone).value.trim();
        console.log(this.state.newPhone);
        if(changePhone == ""){
            alert("请输入新手机号");
        }else if(userSessionStorage.user_phone == changePhone){
            alert("输入的新手机与旧手机号码相同，请重新输入");
        }
        else {
            this.uploadData();
        }
    }

    // 提交user_phone，user_id到服务器，她们写的是GET方法，提交现在的新手机号，和用户职信号，密码那边是提交旧密码，新密码，用户职信号
    uploadData(){
        fetch("http://121.196.202.247:1010/tuser/?user_id="+this.state.loginID+"&user_phone="+this.state.newPhone, {
            method: "GET",
            headers: {
                'Accept': 'application/json',
                "Content-Type": "application/json; charset=utf-8"
            }}) .then((response) => response.json())
            .then((responseText) => {
                console.log(responseText+"aaaaaa");
                console.log(JSON.stringify(responseText)+"aaaaaa");
                if(responseText.success_password == 'password changed successfully!'){
                    window.sessionStorage.setItem('userStorage',JSON.stringify(responseText));
                    console.log(window.sessionStorage.getItem('userStorage'));
                    window.localStorage.setItem('userStorage',JSON.stringify(responseText));
                    alert("手机号码修改成功！刷新将会显示。");
                }
            }).catch((error) => {alert(error+"连接职信服务器失败，请查看网络连接状态并刷新页面！")});
    }

    // 新号码后面的值改变监听事件，一改变就setState重新给state中的newPhone
    handleChange(e){
        this.setState({newPhone: e.target.value});
    }

    render(){
        const userSessionStorage = JSON.parse(window.sessionStorage.getItem('userStorage'));
        return(
            <form className="change_phone" onSubmit={function (e) {this.handleSubmit(e)}.bind(this)} ref="changePhoneForm">
                <p>如果您已不再使用之前的手机号请填写新手机号：</p>
                <p>您当前绑定的手机号为：{userSessionStorage.user_phone}</p>
                <p>新号码是：<input type="text" ref="changePhone" value={this.state.newPhone} onChange={this.handleChange.bind(this)}/></p>
                <input type="submit" value="提交" className="change_phone_submit"/>
                <Link to='/home_me_hr'><input type="button" value="返回" className="change_phone_back"/></Link>
            </form>
        );
    }
}

export default ChangePhone;